package com.sychip.fhc.app.wsn.nav

import android.content.Context
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.viewModelScope
import com.fhc.base.EventBusDataIF
import com.fhc.base.EventBusSubGInfo
import com.fhc.base.EventType
import com.fhc.base.FhcFlowEventBus
import com.fhc.base.FlowEventBusData
import com.fhc.usb.UsbDeviceDto
import com.fhc.usb.UsbSerialManager
import com.fhc.usb.UsbSerialParams
import com.sychip.fhc.IS_DEBUG
import com.sychip.fhc.MainApplication
import com.sychip.fhc.app.data.repo.WsnDeviceRepo
import com.sychip.fhc.app.data.repo.WsnDeviceRssiRepo
import com.sychip.fhc.app.data.repo.WsnRssiHisRepo
import com.sychip.fhc.app.data.source.dto.DevType
import com.sychip.fhc.app.data.source.dto.WsnDeviceDto
import com.sychip.fhc.app.data.source.dto.WsnDeviceRssiDto
import com.sychip.fhc.app.pref.AppSetting
import com.sychip.fhc.app.pref.PrefDataStoreIf
import com.sychip.fhc.app.wsn.common.RouteJoin
import com.sychip.fhc.app.wsn.common.RssiInterval
import com.sychip.fhc.app.wsn.common.Second_1
import com.sychip.fhc.base.BaseAppViewModel
import com.sychip.fhc.base.ViewModelStates
import com.sychip.fhc.di.ApplicationScope
import com.sychip.fhc.di.DefaultDispatcher
import com.sychip.fhc.di.IoDispatcher
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted.Companion.Eagerly
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber
import javax.inject.Inject
import kotlin.math.floor
import kotlin.math.roundToInt

data class WsnTabState(
    val showBottomNavbar: Boolean = true,
)

data class WsnUsbStatus(
    var isNew: Boolean = false,
    var usb: UsbDeviceDto? = null,
)

data class RouterAvgPerDto(val fromDevId: String, val toDevId: String, var avg: String = "--", var per: String = "--", var rssi: String = "") : EventBusDataIF

data class RssiState(
    val rssiAllData: MutableList<WsnDeviceRssiDto> = mutableStateListOf(),
    val avgPerData: MutableList<RouterAvgPerDto> = mutableStateListOf(),
    val oldestRoute: MutableList<WsnDeviceRssiDto> = mutableStateListOf()
)

/**
 * ViewModel for the Start screen.
 */
@HiltViewModel
class WsnMainTabViewModel @Inject constructor(
    app: MainApplication,
    private val devRepo: WsnDeviceRepo,
    private val rssiRepo: WsnDeviceRssiRepo,
    private val rssiHisRepo: WsnRssiHisRepo,
    private val prefDataStore: PrefDataStoreIf,
    @IoDispatcher private val dispatcherIO: CoroutineDispatcher,
    @ApplicationScope private val appScope: CoroutineScope,
    @DefaultDispatcher private val dispatcher: CoroutineDispatcher,
) : BaseAppViewModel(app) {
    private val _usbFlow = MutableStateFlow(WsnUsbStatus())

    private var usbInitTime = -1L
    private var appSetting: AppSetting = AppSetting()

    init {
        if(IS_DEBUG) {
            viewModelScope.launch {
//                rssiRepo.deleteAllData("")
//                devRepo.deleteAll("")
//                rssiHisRepo.deleteAll( "")
            }
        }

        prefDataStore.getUsbDevice().map { localUsb ->
            var isNew = false
            if (_usbFlow.value.usb != null) {
                isNew = _usbFlow.value.isNew
            }
            if (localUsb != null && _usbFlow.value.usb != null &&
                localUsb.serialNumber != _usbFlow.value.usb!!.serialNumber
            ) {
                isNew = true
            }
            Timber.i("init getUsbDevice isNew:%s", isNew)
            _usbFlow.update { WsnUsbStatus(isNew = isNew, usb = localUsb) }
            if (UsbSerialManager.instance()?.getActiveDevice() != null) {
                usbInitTime = System.currentTimeMillis()
                startObserveAllRssiData()
                startAvgPerCalculation()
            } else {
                usbInitTime = -1
                stopObserveAllRssiData()
                stopAvgPerCalculation()
            }
        }.launchIn(viewModelScope)

        viewModelScope.launch {
            rssiRepo.deleteDataBefore(24)
        }

        viewModelScope.launch {
            FhcFlowEventBus.subscribe<FlowEventBusData> { event ->
                if (event.dataType == EventType.ClearAllData) {
                    usbInitTime = System.currentTimeMillis()
                    _rssiState = RssiState()
                }else if (event.dataType == EventType.RssiDataFrom) {
                    _rssiState = RssiState()
                    stopObserveAllRssiData()
                    stopAvgPerCalculation()
                    usbInitTime = System.currentTimeMillis()
                    startObserveAllRssiData()
                    startAvgPerCalculation()
                }else if (event.dataType == EventType.ToggleMockJob) {
                    if(Mock_Pause == 0L) Mock_Pause = 6 * Second_1
                    else if (Mock_Pause > 0) Mock_Pause = 0
                }
            }
        }

        prefDataStore.getAppSettings().map { setting ->
            appSetting = setting
            if (IS_DEBUG) {
                Timber.i("<<<<<<<<<<   getAppSettings mockMode %s", appSetting.mockMode)
                if (appSetting.mockMode || UsbSerialManager.instance()?.getActiveDevice() != null) {
                    usbInitTime = System.currentTimeMillis()
                    startMockTest()
                    startObserveAllRssiData()
                    startAvgPerCalculation()
                } else {
                    usbInitTime = -1
                    stopMockTest()
                    stopObserveAllRssiData()
                    stopAvgPerCalculation()
                }
            } else {
                if (UsbSerialManager.instance()?.getActiveDevice() != null) {
                    usbInitTime = System.currentTimeMillis()
                    startObserveAllRssiData()
                    startAvgPerCalculation()
                } else {
                    usbInitTime = -1
                    stopObserveAllRssiData()
                    stopAvgPerCalculation()
                }
            }
        }.stateIn(
            scope = viewModelScope,
            started = Eagerly,
            initialValue = mutableStateOf<AppSetting?>(null)
        )
    }

    private val _rssiStateLock = Any() // 用于同步访问_rssiList的锁
    private var _rssiState: RssiState = RssiState()

    private var allDataJob: Job? = null
    private var avgRssiJob: Job? = null
    private var perRssiJob: Job? = null
    private var mockJob: Job? = null

    fun startMockTest() {
        stopMockTest()
        mockJob = mockRssiData()
    }

    private fun stopMockTest() {
        mockJob?.cancel()
        mockJob = null
    }

    fun startAvgPerCalculation() {
        stopAvgPerCalculation()
        avgRssiJob = calcRssiPer()
        perRssiJob = calcRssiAvg()
    }

    private fun stopAvgPerCalculation() {
        avgRssiJob?.cancel()
        avgRssiJob = null
        perRssiJob?.cancel()
        perRssiJob = null
    }

    /**
     * 开始观察所有RSSI数据
     */
    private fun startObserveAllRssiData() {
        stopObserveAllRssiData()
        allDataJob = rssiRepo.observeAllDataFrom(usbId, usbInitTime).map { dtos ->
            synchronized(_rssiStateLock) {
                _rssiState.oldestRoute.clear()
                _rssiState.rssiAllData.clear()
                _rssiState.rssiAllData.addAll(dtos)
                val oldestRoute = _rssiState.rssiAllData
                    .groupBy { Pair(it.fromDevId, it.toDevId) }
                    .mapValues { (_, dataList) -> dataList.minByOrNull { it.dateTime } }.values
                    .filterNotNull().toList()
                _rssiState.oldestRoute.addAll(oldestRoute)
            }
        }.launchIn(viewModelScope)
    }

    /**
     * 停止观察所有RSSI数据
     */
    private fun stopObserveAllRssiData() {
        allDataJob?.cancel()
        allDataJob = null
    }

    /**
     * 定时计算平均PER
     */
    private fun calcRssiAvg():Job {
        return  viewModelScope.launch {
            while (isActive) {
                withContext(dispatcher) {
                    if (_rssiState.rssiAllData.isEmpty()) {
                        delay(Second_1)
                        return@withContext
                    }
                    synchronized(_rssiStateLock) {
                        val rssiStateNew = _rssiState.copy()

                        val groupedData = rssiStateNew.rssiAllData.groupBy { Pair(it.fromDevId, it.toDevId) }
                        groupedData.toMap().forEach { (keyPair, rssiList) ->
                            val avgRssi = rssiList.takeLast(
                                appSetting.avgNums
                            ).map { it.rssi }.average().roundToInt().toString() // 若列表元素不足_avgNum，上述方法会自动返回全部元素，无需额外判空
                            var avgDto = rssiStateNew.avgPerData.find {
                                it.fromDevId == keyPair.first && it.toDevId == keyPair.second
                            }
                            if (avgDto == null) {
                                avgDto = RouterAvgPerDto(keyPair.first, keyPair.second)
                                rssiStateNew.avgPerData.add(avgDto)
                            }
                            avgDto.avg = avgRssi
                            avgDto.rssi = rssiList.last().rssi.toString()
                            FhcFlowEventBus.publish(FlowEventBusData(EventType.AvgPer, avgDto))
                        }
                        _rssiState = rssiStateNew
                    }

                    delay(Second_1)
                }
            }
        }
    }

    private fun calcRssiPer():Job {
        return viewModelScope.launch {
            while (isActive) {
                withContext(dispatcher) {
                    if (_rssiState.rssiAllData.isEmpty()) {
                        delay(RssiInterval)
                        return@withContext
                    }
                    synchronized(_rssiStateLock) {
                        val rssiStateNew = _rssiState.copy()
                        rssiStateNew.oldestRoute.forEachIndexed { index, dtoOldest ->
                            val currentMS = System.currentTimeMillis()
                            if (currentMS - dtoOldest.dateTime >= RssiInterval * 3) {
                                val receiveRssiList = rssiStateNew.rssiAllData.filter {
                                    it.fromDevId == dtoOldest.fromDevId &&
                                            it.toDevId == dtoOldest.toDevId &&
                                            it.dateTime >= dtoOldest.dateTime
                                }
                                // 1) how many RSSI packets the USB dongle gateway received for that route
                                val receiveCnt = receiveRssiList.size
                                // 往前推4秒才算开始,在减去-5毫秒，是为了运算有点偏差,否则：5秒内有俩数据，期望是5/4=1.25,实际是2，丢包率会为负值
                                val elapsed = -5 + RssiInterval + (currentMS - dtoOldest.dateTime)
                                // the elapsed time since the user selects the route.
                                var avgDto = rssiStateNew.avgPerData.find {
                                    it.fromDevId == dtoOldest.fromDevId && it.toDevId == dtoOldest.toDevId
                                }
                                if (avgDto == null) {
                                    avgDto = RouterAvgPerDto(dtoOldest.fromDevId, dtoOldest.toDevId)
                                    rssiStateNew.avgPerData.add(avgDto)
                                }
                                val expectCnt = floor(
                                    elapsed / (RssiInterval * 1.0)
                                )
                                // The RSSI packets should be sent to the USB gateway
                                // every 4 seconds if the communication is good.
                                val psr = receiveCnt / expectCnt
                                var per = ((1 - psr) * 100).roundToInt()
                                if (per < 0) {
                                    Timber.e("PER < 0 : %s -- %s   usbInitTime:%s  dateTime:%s  currentMS: %s    elapsed:%s  receiveCnt:%s    expectCnt:%s   psr:%s   per:%s", dtoOldest.fromDevId, dtoOldest.toDevId, usbInitTime, dtoOldest.dateTime, currentMS, elapsed, receiveCnt, expectCnt, psr, per)
                                    per = 0
                                }
                                avgDto.per = per.toString()
                                FhcFlowEventBus.publish(FlowEventBusData(EventType.AvgPer, avgDto))
                            }
                        }
                    }
                    delay(RssiInterval)
                }
            }
        }
    }

//    fun generateRandomHexString(): String {
//        val hexChars = ('0'..'9') + ('a'..'f')
//        return buildString {
//            repeat(4) {
//                append(hexChars.random())
//            }
//        }
//    }

    private fun updateUsbState(status: WsnUsbStatus) {
        _usbFlow.update { status }
        if (status.usb != null && status.usb!!.online) {
            usbInitTime = System.currentTimeMillis()
            startObserveAllRssiData()
            startAvgPerCalculation()
        } else {
            usbInitTime = -1
            stopObserveAllRssiData()
            stopAvgPerCalculation()
        }
    }

    var Mock_Pause = 0 * Second_1
    val Mock_Delay = 1 * Second_1

    private fun mockRssiData():Job {
        Timber.e("mockRssiData   mockRssiData   mockRssiData >>> " )
//        If you don't need to monitor real-time test data constantly,
        //        The following steps might be a more efficient and time-saving approach.
//        FYI
//        Click the repeater/sensor(s) of route you want to monitor, take picture to record locations with notes.
//        Click "One-Tap Test" (displays the route list from Step 1), input test duration, and confirm to begin.
//        APP will keep the screen on during this time.
        //        A countdown timer will display based on the test duration
        //        (users may set aside the tablet for other tasks; the APP supports test cancellation or restart).
//        The APP will automatically save test records upon completion and play a sound notification.
//        Users generate test reports based on the saved records.
        return viewModelScope.launch {

            val GW = "7FFF"
            val bc42 = "BC42"
            val b322 = "B322"
            val c973 = "C973"
            val a912 = "A912"

            while (isActive) {
                if (!appSetting.mockMode) return@launch
                val rssi12 = (0..107).random().toString(16).padStart(2, '0').takeLast(2)

                val rssi78 = (0..100).random().toString(16).padStart(2, '0').takeLast(2)
                val s_bc42 = bc42 + (50..106).random().toString(16).padStart(2, '0').takeLast(2)
                val s_b322 = b322 + (0..80).random().toString(16).padStart(2, '0').takeLast(2)
                val s_a912 = a912 + (0..50).random().toString(16).padStart(2, '0').takeLast(2)
                val s_c973 = c973 + (0..50).random().toString(16).padStart(2, '0').takeLast(2)
//
                viewModelScope.launch {
                    //bc42    7FFF
                    var dev = bc42
                    _usbDataChannel.send("ERXDATA $dev 0000 2B9B 1000 $rssi12 05 +FF0A $dev $GW")

                    delay(50)
                    dev = b322
                    _usbDataChannel.send("ERXDATA $dev 0000 2B9B 1000 $rssi12 05 +FF0A $dev $GW")
                }

                delay(Mock_Delay)
                if (!appSetting.mockMode) return@launch
                viewModelScope.launch {
                    //bc42  a912  7FFF
                    var dev = s_bc42
                    _usbDataChannel.send("ERXDATA $c973 0000 2B9B 1000 $rssi78 05 +FE0A$dev $c973 $GW")

                    delay(50)
                     dev = s_b322
                    _usbDataChannel.send("ERXDATA $c973 0000 2B9B 1000 $rssi78 05 +FE0A$dev $c973 $GW")

                }

                delay(Mock_Delay)
                if (!appSetting.mockMode) return@launch
                viewModelScope.launch {
                    //bc42  a912  7FFF
                    var dev = s_bc42
                    _usbDataChannel.send("ERXDATA $a912 0000 2B9B 1000 $rssi78 05 +FE0A$dev $a912 $GW")

                    delay(50)
                    dev = s_b322
                    _usbDataChannel.send("ERXDATA $a912 0000 2B9B 1000 $rssi78 05 +FE0A$dev $a912 $GW")

                }

                delay(Mock_Delay)
                if (!appSetting.mockMode) return@launch
                viewModelScope.launch {
                    //bc42  c973 a912   7FFF
                    var dev = s_bc42
                    _usbDataChannel.send("ERXDATA $a912 0000 2B9B 1000 $rssi78 05 +FF0A$s_bc42$s_c973 $a912 $GW")

                    delay(50)
                    dev = s_b322
                    _usbDataChannel.send("ERXDATA $a912 0000 2B9B 1000 $rssi78 05 +FF0A$s_bc42$s_c973 $a912 $GW")
                }

                delay(Mock_Delay)
                if (!appSetting.mockMode) return@launch
                viewModelScope.launch {
//                bc42  a912   c973  7FFF
                    var dev = s_bc42
                    _usbDataChannel.send("ERXDATA $c973 0000 2B9B 1000 $rssi78 05 +FF0A$dev$s_a912 $c973 $GW")

                    delay(50)
                    dev = s_b322
                    _usbDataChannel.send("ERXDATA $c973 0000 2B9B 1000 $rssi78 05 +FF0A$dev$s_a912 $c973 $GW")
                }


                delay(Mock_Delay)
                if (!appSetting.mockMode) return@launch

                delay(Mock_Delay)
            }
        }
    }

    override fun initUICommonState(): ViewModelStates {
        return ViewModelStates.Loading
    }

    private val _tabStateFlow = MutableStateFlow(WsnTabState(true))
    val tabStateFlow: StateFlow<WsnTabState> = _tabStateFlow.asStateFlow()

    fun showBottomNavbar(show: Boolean) {
        _tabStateFlow.update { WsnTabState(show) }
    }

    private var usbManager: UsbSerialManager? = null
//    private val mutex = Mutex() // 定义全局互斥锁
//    private suspend fun parseRssiData(str:String) {
//        mutex.withLock {
//            //ERXDATA C76A 0000 2B9B 1000 58 05 +FE0A C76A 97C1
//            withContext(dispatcherIO) {
//                parseUsbSerialData(str)
//            }
//        }
//    }

    private val _usbDataChannel = Channel<String>(capacity = 64)

    // 定义数据接收回调
    private val usbDataReceiver: (String) -> Unit = { data ->
        // 处理接收到的数据
        // ERXDATA C76A 0000 2B9B 1000 58 05 +FE0A C76A 97C1
//        viewModelScope.launch{
//            parseRssiData(data)
//        }

        viewModelScope.launch {
            _usbDataChannel.send(data) // 非阻塞式投递数据
        }
    }

    private fun buildUsbDataConsumeChannel() {
        viewModelScope.launch {
            _usbDataChannel.consumeAsFlow().collect { data ->
                launchParseUsbSerialTask(data)
            }
        }
    }

    private fun launchParseUsbSerialTask(data: String) {
        viewModelScope.launch {
            // 有必要的话通知UI，比如设置UICommonState等
            try {
                withContext(dispatcherIO) {
                    parseUsbSerialData(data)
                }
            } catch (_: Exception) {
                // 有必要的话通知UI，比如设置UICommonState等
            }
        }
    }

    private val _serialDataFlow = MutableStateFlow("")
    val serialDataFlow: StateFlow<String> = _serialDataFlow.asStateFlow()
    fun clearSerialData() {
        _serialDataFlow.update { "" }
    }

    private suspend fun parseUsbSerialData(str: String) {

        val allDevs: MutableList<WsnDeviceDto> = mutableListOf()
        devRepo.getAllWsnDevices(usbId = usbId).collect {
            allDevs.addAll(it)
        }
        val current = System.currentTimeMillis()
        val data = str.split("\r\n").first().split(" ")
        if (data[0] == "ERXDATA" && data.size >= 9 && data[4] == "1000") {
            var rssiParse = ""
            val payload = data[7]
            if (payload.startsWith("+") || payload.startsWith("*")) {
                val lastRssi = data[5].toInt(16) - 107
                val rssiData = mutableListOf<Int>()
                val routerData = mutableListOf<String>()

                if (data[7].length > 5) {
                    val pathData = data[7].substring(5)
                    for (i in 0 until pathData.length step 6) {
                        routerData.add(pathData.substring(i, i + 4))
                        rssiData.add(pathData.substring(i + 4, i + 6).toInt(16) - 107)
                    }
                }
                rssiData.add(lastRssi)
                for (i in 8 until data.size) {
                    routerData.add(data[i].substring(0, 4))
                }
                Timber.e("parseUsbSerialData >>> %s    %s    %s", routerData, rssiData, str)
                routerData.forEachIndexed { index, devId ->
                    val dto = allDevs.find { dev -> dev.devId == devId }
                    if (dto == null) {
                        // 最后是gateway
                        // 如果   +FE，那所有的都是repeater，除了最后是gateway
                        // 如果非 +FE，那第一个sensor，中间都是是repeater，除了最后是gateway
                        val devType = if (index == routerData.size - 1) {
                            DevType.Gateway
                        } else {
                            if (!payload.startsWith("+FE")) {
                                if (index == 0) {
                                    DevType.Sensor
                                } else {
                                    DevType.Repeater
                                }
                            } else {
                                DevType.Repeater
                            }
                        }
//                      Timber.e("parseUsbSerialData  createWsnDevice111111  >>>  route:%s    devType:%s     ",it.uppercase(),  devType.name)
                        devRepo.createWsnDevice(
                            usbId = usbId,
                            devId = devId.uppercase(),
                            devType = devType.name,
                            lastData = str,
                            offsetX = -1f,
                            offsetY = -1f
                        ).collect {
                            allDevs.add(it)
                            Timber.e("createWsnDevice  222222222222  >>>  route:%s    devType:%s     ",it,  devType.name)
                        }

                        delay(2)
                    }else{
                        devRepo.updateLastData(usbId, devId, str)
                    }
                }

                for (i in 0 until routerData.size - 1) {
                    val fromDevId = routerData[i].uppercase()
                    val toDevId = routerData[i + 1].uppercase()
                    val dtoFromDev = allDevs.find { dev -> dev.devId == fromDevId }
                    val dtoToDev = allDevs.find { dev -> dev.devId == toDevId }
                    if(dtoFromDev?.devType == DevType.Repeater.name
                        && dtoToDev?.devType == DevType.Repeater.name){
                        Timber.e("createWsnDevice  Repeater  Repeater  Repeater:%s    :%s     ",fromDevId, toDevId)

                    }
                    rssiRepo.addRssiData(
                        usbId = usbId,
                        fromDevId = routerData[i].uppercase(),
                        toDevId = routerData[i + 1].uppercase(),
                        rssi = rssiData[i].toString(),
                        dateTime = current
                    )
                    Timber.e("addRssiData   >>>  %s --  %s (%s)",routerData[i],  routerData[i + 1].uppercase(), rssiData[i])
                    delay(2)
                    rssiParse = "$rssiParse$fromDevId$RouteJoin$toDevId,"
                    //数据以BC42 --> A912,A912 --> C973,C973 --> 7FFF, 格式存放，每一组包含fromDevId  toDevId
                }
            }
            rssiHisRepo.add(usbId, str ,0, rssiParse, dateTime = current)
        } else if (data[0] == "ENETINFO" && data.size >= 5) {
            if (IS_DEBUG) _serialDataFlow.update { str }
            // ENETINFO 1C 1010 0D9C 7FFF 0
            // ENETINFO 21 EA60 7777 FFFF 0      EA60 = 60,000
            val usbEvent = EventBusSubGInfo()
            usbEvent.channel = data[1]
            usbEvent.port = data[2]
            usbEvent.panId = data[3]
            usbEvent.encryption = data[5] == "1"

            FhcFlowEventBus.publish(FlowEventBusData(EventType.UsbData, usbEvent))
            rssiHisRepo.add(usbId, str ,1, "", dateTime = current)
        } else {
            if (IS_DEBUG) _serialDataFlow.update { str }
            Timber.e("XXXXXXXXXXXXXXXX  parseUsbSerialData  >>> %s", str)
            rssiHisRepo.add(usbId, str ,9, "", dateTime = current)
        }
    }

    fun initUsbSerialManager(context: Context) {
        // 创建 UsbSerialManager 实例
        usbManager = UsbSerialManager.getInstance(context, UsbSerialParams(), usbDataReceiver)
        if (usbManager == null) {
            Timber.i("initUsbSerialManager   usbManager  is  null")
            return
        }
        usbManager?.let {
            buildUsbDataConsumeChannel()
            it.requestPermission()
            // 检查是否有权限并打开设备
            if (it.hasPermission()) {
                it.openDevice { dto ->
                    Timber.i("initUsbSerialManager  productName  ----   %s", dto.productName)

                    val usbActive = dto
                    val localUsb = _usbFlow.value.usb
                    if (localUsb != null) {
                        viewModelScope.launch {
                            val isSame = prefDataStore.compareUsbDevice(localUsb, usbActive)
                            if (!isSame) {
                                Timber.i("initUsbSerialManager  compareUsbDevice isNew:%s", true)
                                updateUsbState(WsnUsbStatus(isNew = true, usb = usbActive))
                            }
                            usbActive.online = true
                            prefDataStore.saveUsbDevice(usbActive)
                        }
                    } else {
                        viewModelScope.launch {
                            Timber.i("initUsbSerialManager  localUsb null isNew:%s", false)
                            usbActive.online = true
                            updateUsbState(WsnUsbStatus(isNew = false, usb = usbActive))
                            prefDataStore.saveUsbDevice(usbActive)
                        }
                        Timber.i("  initUsbSerialManager  0000 -----------------还没有usb插入过 ")
                    }
                }
                Timber.i("initUsbSerialManager  UsbSerial  1111 -----------------有有有 USB 权限")
            } else {
                Timber.i("initUsbSerialManager  UsbSerial  2222 -----------------没没没 USB 权限")
            }
        }
    }

    fun destoryUsbSerialManager() {
        val usbActive = _usbFlow.value.usb
        if (usbActive != null) {
            viewModelScope.launch {
                usbActive.online = false
                prefDataStore.saveUsbDevice(usbActive)
                updateUsbState(_usbFlow.value)
            }
        }
        usbManager?.closeDevice()
        usbManager = null
    }

    override fun onCleared() {
        destoryUsbSerialManager()
        stopAvgPerCalculation()
        stopObserveAllRssiData()
        stopMockTest()
        super.onCleared()
    }
}
